﻿using MediatR;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;
using RBAC_Class.Write.API.Application.Command.Roles;

namespace RBAC_Class.Write.API.Application.CommandHandler.Roles
{
    public class UpdateRoleCommandHandler:IRequestHandler<UpdateRoleCommand,APIResult<int>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<RolePermission> rolePermissionRep;
        private readonly ILogger<UpdateRoleCommandHandler> logger;
        public UpdateRoleCommandHandler(IBaseRepository<Role> roleRep, IBaseRepository<RolePermission> rolePermissionRep, ILogger<UpdateRoleCommandHandler> logger)
        {
            this.roleRep = roleRep;
            this.rolePermissionRep = rolePermissionRep;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            
            var list = roleRep.GetAll().FirstOrDefault(x => x.RoleID == request.RoleID);

            using (var tran = roleRep.Context.Database.BeginTransaction())
            {
                try
                {
                    list.RoleName = request.RoleName;
                    roleRep.Update(list);
                    if(request.permissionID != null)
                    {
                        var delepermission = rolePermissionRep.GetAll().Where(x => x.RoleID == request.RoleID);
                        foreach(var item in delepermission)
                        {
                            item.IsDelete = true;
                            rolePermissionRep.Update(item);
                        }
                    }
                    foreach (var item in request.permissionID)
                    {
                        var rolepermission = new RolePermission
                        {
                            RoleID = request.RoleID,
                            PermissionID = item,
                            CreateTime = DateTime.Now,
                            IsDelete = false
                        };
                        rolePermissionRep.Add(rolepermission);
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    logger.LogError("修改出错", ex);
                    tran.Rollback();
                }
            }
            
            return Task.FromResult(new APIResult<int>()
            {
                Code = ResultCode.Success,
                Message = "修改成功",
                Data = 1
            });
        }
    }
}   
